package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import com.atguigu.yygu.common.resulit.Result;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送手机验证码
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码 key是手机号 value是验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotBlank(code)) {
            return Result.ok();
        }
        //工具类生成六位验证码
        code = RandomUtil.getSixBitRandom();
        //通过短信服务发送验证码
        boolean isSend = msmService.send(phone, code);
        if (isSend) {
            //设置key value 过期时间 时间单位
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败!");
        }
    }
}
